require(['jquery','../modules/popup','../modules/pageSize','../modules/LArea'],function($, popup, pageSetSize){
    setRootFontSize(pageSetSize);
    var district = [0, 0, 0];
    var _dis_rs = {
        _province : '',
        _city :'',
        _district : ''
    };
    var dis_obj='';
    var isFirst = true;
    var isInBMFunc = false;
    popup.loadPopup("正在定位中...");
    function ShowPageWithAlert(type, msg){
        if(isFirst){
            isFirst = false;
            popup.removeLoad();
        }
        if(type == 1){
            alert(msg);
        }
    }
    setTimeout(function(){
        if(isFirst){
            isFirst = false;
            if(!isInBMFunc){
                isInBMFunc = true;
                popup.removeLoad();
                popup.alertPopup("定位超时，请手动选择！");
                LAreaRes(_dis_rs);
            }
        }
    },4000);
    /**
     * 首次进入通过微信定位
     */
    if (source == 1) {
        wx.config({
            debug: false,
            appId: wx_config.appId,
            timestamp: wx_config.timestamp,
            nonceStr: wx_config.nonceStr,
            signature: wx_config.signature,
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                'checkJsApi',
                'getLocation'
            ]
        });
        wx.ready(function () {
            wx.checkJsApi({
                jsApiList: [
                    'getLocation'
                ],
                success: function (res) {
                    if (res.checkResult.getLocation == false) {
                        var msg = '你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！';
                        ShowPageWithAlert(1, msg);
                    }
                }
            });
            wx.getLocation({
                success: function (res) {
                    var lat = res.latitude;      // 纬度，浮点数，范围为90 ~ -90
                    var lng = res.longitude;     // 经度，浮点数，范围为180 ~ -180。
                    var speed = res.speed;        // 速度，以米/每秒计
                    var accuracy = res.accuracy;  // 位置精度
                    if(!isInBMFunc) {
                        ShowPageWithAlert(2);
                        BMapGetLocation(lng, lat);
                    }
                },
                cancel: function (res) {
                    var msg = '用户拒绝授权获取地理位置！';
                    ShowPageWithAlert(1, msg);
                }
            });
            wx.error(function(res){
                setRootFontSize(pSetSize);
            });
        });
    }
    //BMapGetLocation('106.535645','29.61527');
    function BMapGetLocation(lon, lat) {
        if(!isInBMFunc){
            isInBMFunc = true;
        }
        var pt = new BMap.Point(lon, lat);
        var gc = new BMap.Geocoder();
        var addComp;
        //获取地址的数据地址
        gc.getLocation(pt, function (rs) {
            addComp = rs.addressComponents;
            var address = addComp.province + '/' + addComp.city + '/' + addComp.district;
            document.getElementById("address_detail").value = address;
            var dis_set = address;
            area_spilt(dis_set);
            ajaxSLocation(addComp.province, addComp.city, addComp.district, lon, lat);
        });
    }
    function area_spilt(dis_set){
        if(dis_set){
            _dis_rs._province = dis_set.split('/')[0];
            _dis_rs._city = dis_set.split('/')[1];
            _dis_rs._district = dis_set.split('/')[2];
        }
        LAreaRes(_dis_rs);
    }
    /* 加载省市区数据 */
    function LAreaRes(dis_rs){
        $.ajax({
            'url': '/Home/First/regions' + getFixedExtraUrl(),
            'type': 'get',
            'success': function (data) {
                if(data){
                    dis_obj = $.parseJSON(data);
                    newLArea(dis_rs,dis_obj);
                }
            }
        });
    }
    function newLArea(dis_rs,obj){
        var curObj;
        var tList;
        if(dis_rs._province != '' && dis_rs._city != '' && dis_rs._district != ''){
            for(var i = 0; i<dis_obj.length; i++){
                curObj = dis_obj[i];
                if(dis_rs._province == curObj.name){
                    district[0]= i;
                    break;
                }
            }
            tList = curObj.child;
            for(var i = 0; i < tList.length; i++){
                curObj = tList[i];
                if(dis_rs._city == curObj.name){
                    district[1]= i;
                    break;
                }
            }
            tList = curObj.child;
            for(var i = 0; i < tList.length; i++){
                curObj = tList[i];
                if(dis_rs._district == curObj.name){
                    district[2]= i;
                    break;
                }
            }
        }
        var area = new LArea();
        area.init({
            'trigger': '#address_detail',
            'valueTo': '#addressValue',
            'keys': {
                id: 'id',
                name: 'name'
            },
            'type': 1,
            'data': obj
        });
        area.value = district;
    }

    function ajaxSLocation(province, city, district, lon, lat) {
        var _data = {'lng': "", 'lat': "", 'province': province, 'city': city, 'district': district};
		$(".area-shop-list").html("");
        popup.loadPopup("正在处理中...");
        $.ajax({
            url:'/Home/First/placeStortSelect' + getFixedExtraUrl(),
            data:_data,
            dataType:'json',
            success:function(rs){                
                if (rs == null) {
					popup.removeLoad();
                    $(".area-shop-list").text('你查询的门店还未开通...');
                    $(".area-shop-list").css({color: "#787878", fontSize: '.28rem', padding: '.24rem'});
                }
                else {
                    $(".area-shop-list").css({padding: '0'});
                    if (rs.error) {
						popup.removeLoad();
                        popup.alertPopup(rs.msg);
                    } else {
                        var html = '';
                        for (var i = 0; i < rs.length; i++) {
                            html += '<a class="shop-item" href="/First/doStortSelect/local_id/'+rs[i].local_id+'"><p>' + rs[i].local_name + '</p><p>' + rs[i].area_text + '</p></a>';
                        }
                        $(".area-shop-list").html(html);
						popup.removeLoad();
                    }
                }
				
            },
            error:function(){
                popup.removeLoad();
                popup.alertPopup('服务器异常,请稍后重试！');
            }
        });
    }
    /* 通过手动选择定位 */
    $("#address_detail").bind('input porpertychange',function(){
            var addres_rs = $(this).val(),
                _province = addres_rs.split('/')[0],
                _city = addres_rs.split('/')[1],
                _district = addres_rs.split('/')[2];
            ajaxSLocation(_province, _city, _district, "", "");
    })
});